﻿using AutoMapper;
using MediatR;
using Microsoft.EntityFrameworkCore.Migrations;
using RearLivestock.Common.Domains.wbx;
using RearLivestock.Common.Dtos;
using RearLivestock.Common.Infrastructure.Interface;
using RearLivestock.RBAC.ErrorCodeEnum;

namespace RearLivestock.Beginning.Api.Application.Command.PigWeighings
{
    /// <summary>
    /// 猪只称重添加Handler
    /// </summary>
    public class AddPigsWeighingHandler : IRequestHandler<AddPigsWeighingCommand, Result>
    {
        private readonly IMapper mapper;
        /// <summary>
        /// 猪只称重
        /// </summary>
        private readonly IBaseRepository<PigsWeighing> pigsWeighingrepository;
        /// <summary>
        /// 日志
        /// </summary>
        private readonly ILogger<AddPigsWeighingHandler> _logger;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="mapper"></param>
        /// <param name="pigsWeighingrepository"></param>
        /// <param name="logger"></param>
        public AddPigsWeighingHandler(IMapper mapper, IBaseRepository<PigsWeighing> pigsWeighingrepository, ILogger<AddPigsWeighingHandler> logger)
        {
            this.mapper = mapper;
            this.pigsWeighingrepository = pigsWeighingrepository;
            _logger = logger;
        }

        /// <summary>
        /// 猪只称重
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        public async Task<Result> Handle(AddPigsWeighingCommand request, CancellationToken cancellationToken)
        {
            var result = new Result() { Code = (int)CommonErrorCode.Added };
            try
            {
                PigsWeighing pigsWeighing= mapper.Map<PigsWeighing>(request);
                var res = await pigsWeighingrepository.Add(pigsWeighing);
                if (res > 0)
                {
                    result.Code = (int)CommonErrorCode.Success;
                }
                result.Msg = "猪只称重添加成功";
            }
            catch (Exception ex)
            {
                _logger.LogError("猪只称重添加失败" + ex.Message);
                throw;
            }
            return result;
        }
    }
}
